<script lang="ts" setup>
import {onHide, onLaunch, onShow} from "@dcloudio/uni-app";
import {checkUserStatusApi, userLogin} from "@/api/user";
import {useUserStore} from "@/stores/user";
import {isTimestampToday} from "@/utils/time";
import {listenPush, pushMsg, setBadge} from "@/utils/pushUtil";
import socket from 'plus-websocket'
import {WS_URL} from "@/constant/websocketConstant";
import {useBadgeStore} from "@/stores/badgeNum";
import {IMessage} from "@/components/aw-message/message";
import {GlobePopupType} from "@/enum/globePopupType";

const userStore = useUserStore()
const badgeStore = useBadgeStore()
onLaunch(async () => {
  /**
   * 用户账号锁定时触发
   * @param msg
   */
  const onUserLocked = (msg: pushMessage) => {
    uni.navigateTo({
      url: '/pages/globePopup/globePopup?type=' + GlobePopupType.LOCKED
    })
    IMessage({
      content: "用户账号被锁定，请重新登录",
      type: "error",
      showIcon: true
    })
    setBadge(0)
    pushMsg(msg, 'error')
    userStore.clearUserInfo()
    badgeStore.clearBadge()
    // #ifndef APP-PLUS
    uni.reLaunch({
      url: '/subPkg/login/login'
    })
    // #endif
  }

  /**
   * 判断当前是否需要动态更新页面消息数
   * @param msg 消息内容
   */
  const checkUpdateBadge = (msg: pushMessage): boolean => {
    if (msg.type !== 'chat') {
      return false
    }
    // 1、判断当前是否在my页面和消息列表页面
    const currentPages = getCurrentPages()
    // 获取当前用户所在页面
    const route = currentPages[currentPages.length - 1].route
    console.log('当前页面：', route)
    if (route === 'pages/my/my') {
      uni.$emit('updateMyBadge', msg)
    } else if (route === 'subPkg/message/message') {
      uni.$emit('updateChatList', msg)
    }
    return true
  }
  const checkUserStatus = async () => {
    // 每次进入app向服务器发送账号确认，判断该用户是否被锁定
    return await checkUserStatusApi()
  }
  /**
   * 建立链接
   */
  if (userStore.userInfoData?.token) {
    // 确认用户账号信息
    const {data} = await checkUserStatus()

    let socketTask = socket.connectSocket({
      url: 'ws://' + WS_URL + '/ws/message?userId=' + userStore.userInfoData?.userID + '&token=' + userStore.userInfoData?.token,
      success: () => {
        console.log('WebSocket连接已建立');
      },
      fail: (err: any) => {
        console.log('WebSocket连接建立失败')
        console.log(err)
      }
    })

    /**
     * 连接打开
     */
    socketTask.onOpen(async () => {
      console.log('WebSocket连接已打开')

      // 获取用户每日登录信息
      if (!data) {
        // 用户账号异常不需要进行其他操作
        return
      }

      const dailyLoginTime: number = userStore.dailyLoginTime
      const isToday = isTimestampToday(dailyLoginTime)
      if (!isToday && userStore.userInfoData) {
        const res = await userLogin()
        userStore.dailyLoginTime = Date.now()
        // 更新本地缓存
        if (res.data?.token) {
          userStore.userInfoData = res.data
        }
      } else {
        // 是今天则不做任何处理或者用户未登录也不做处理
      }
    })

    /**
     * l接收到消息
     */
    socketTask.onMessage((data: any) => {
      const msg = JSON.parse(data.data) as pushMessage
      console.log('收到服务器内容：', data)
      // 检查该消息是否是下线消息
      if (msg.code) {
        if (Number(msg.code) === 1000) {
          onUserLocked(msg)
          return
        }
      }

      // 判断是否需要动态更新页面消息数
      const isChat = checkUpdateBadge(msg)
      if (isChat) {
            msg.title = '【新消息】@' + msg.title
      }

      if (msg.increaseCount) {
        uni.setTabBarBadge({
          index: 3,
          text: badgeStore.badge + msg.increaseCount
        })
        // setBadge(badgeStore.badge + msg.increaseCount)
      }

      uni.$emit('onMsg', msg)
    })
    socketTask.onClose(() => {
      console.log('WebSocket连接已关闭')
    })
  }
  // 用户登录

  //禁止屏幕旋转
  // #ifdef APP-PLUS
  plus.screen.lockOrientation("portrait-primary")
  //设置当前app原生主题
  plus.nativeUI.setUIStyle("auto")
  // #endif
  listenPush()
  // 监听底部tabBar点击事件
  uni.onTabBarMidButtonTap(() => {
    if (!userStore.userInfoData) {
      return uni.showToast({title: '请先登录', icon: 'error'})
    }
    uni.navigateTo({
      url: '/subPkg/uploadChoose/uploadChoose',
    });
  })
})
onShow(() => {
});
onHide(() => {
})
</script>
<template></template>
<style>
@import "static/colorui/main.css";
@import "static/colorui/icon.css";
</style>
